package com.neasho.neashoadminv1.infrastructure.inteceptor

import com.neasho.neashoadminv1.infrastructure.permission.ApiAuthInterceptor
import com.neasho.neashoadminv1.infrastructure.permission.UserContextInitInterceptor
import com.neasho.neashoadminv1.infrastructure.utils.TraceIdInterceptor
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer


@Configuration
class InterceptorConfig(
    val apiAuthInterceptor: ApiAuthInterceptor,
    val userContextInitInterceptor: UserContextInitInterceptor,
    val traceIdInterceptor: TraceIdInterceptor
): WebMvcConfigurer {
    override fun addInterceptors(registry: InterceptorRegistry) {
        // 注册Mdc拦截逻辑
        registerMdcIdeInterceptor(registry)
        // 注册UserContext拦截逻辑
        registerUserContextInterceptor(registry)
        // 注册ApiAuth拦截起
        registerApiAuthInterceptor(registry)
    }

    private fun registerMdcIdeInterceptor(registry: InterceptorRegistry) {
        registry.addInterceptor(traceIdInterceptor)
            .addPathPatterns("/**")
            .excludePathPatterns("/error")
            .excludePathPatterns("/actuator/**")
            .excludePathPatterns("/swagger-ui/**")
            .excludePathPatterns("/v3/api-docs/**")
    }


    /**
     * 无需授权的白名单
     */
    val noPermissionUris = listOf<String>(
        "/console/login",
        "/console/logout",
        "/error",
        "/actuator/**",
        "/swagger-ui/**",
        "/v3/api-docs/**",
        "/openapi.html",
        "/openapi.yaml",
    )
    // 注册一个interceptor用来检查权限
    private fun registerUserContextInterceptor(registry: InterceptorRegistry) {
        registry.addInterceptor(userContextInitInterceptor)
            .addPathPatterns("/**")
            .excludePathPatterns(noPermissionUris)
    }

    private fun registerApiAuthInterceptor(registry: InterceptorRegistry) {
        registry.addInterceptor(apiAuthInterceptor)
            .addPathPatterns("/**")
            .excludePathPatterns(noPermissionUris)
    }
}